package fr.imag.m2pgi.m2m.geoloc.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JOptionPane;

import org.osgi.util.tracker.ServiceTracker;

import fr.imag.m2pgi.m2m.geoloc.Lidar;
import fr.imag.m2pgi.m2m.geoloc.mqtt.publisher.PublishService;

public class AddMeasureListener implements ActionListener {

  private MainFrame main;
  private PublishService publish;
  private ServiceTracker<PublishService, PublishService> trackerPub;
  
  public AddMeasureListener(MainFrame main) {
    this.main = main;
  }
  
  public void setPublisher(PublishService publish,ServiceTracker<PublishService, PublishService> trackerPub)
  {
    this.publish = publish;
    this.trackerPub = trackerPub;
  }
  public void actionPerformed(ActionEvent arg0) {
    Integer z = main.getZ();
    if(z==null) {
      error("You must set the Z field.");
      return;
    }
//    ArrayList<Double> angles = main.getAngles();
//    if(angles.isEmpty()) {
//      error("You must choose at least 1 angle.");
//      return;
//    } else {
//      System.out.println("Getting "+angles.size()+" angles");
//    }
//    if(main.getVisualizer()==null) {
//      error("No visualizer available.");
//      return;
//    }
    try {
      ArrayList<Integer> rawData = main.getLidar().getMeasures();
      HashMap<Double, Integer> data = new HashMap<Double, Integer>(rawData.size());
//      for(double angle : angles) {
//        System.out.println("Getting angle "+angle+"°...");
//        int m = main.getLidar().getRange(rawData, angle);
//        data.put(-1*angle, m);
//      }
      for(double angle=-90d; angle<=90d; angle++) {
        int m = main.getLidar().getRange(rawData, angle);
        data.put(-1*angle, m);
      }
      System.out.println("Got "+data.size()+" angles");
//      main.getVisualizer().addMeasure(data, z);
      while(publish == null) {
        System.err.println("No service, waiting for one...");
        publish = trackerPub.waitForService(1000);
      }
      publish.sendMessage(z, data);
      
    } catch (IOException e) {
      error("Error retrieving measures.");
      return;
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  private void error(String msg) {
    JOptionPane.showMessageDialog(main, msg,
        "Invalid fields", JOptionPane.ERROR_MESSAGE);
  }
  
}
